Android 7.0 Notification Sound Issue

前言

最近遇到一个问题:
自定义Notification通知声音(一个外部存储MP3文件),Android7.0版本上无法正常播放。

分析

  1. 查阅代码是否正常执行,setSound是否设置有效Uri正常执行,设置的Uri有效
  2. 查看Log发现权限问题相关Log
1
MediaPlayer: Couldn't open content://xxxxxxxx/new_order.mp3: java.lang.SecurityException: Permission Denial: opening provider android.support.v4.content.FileProvider from ProcessRecord{ce87f22 2005:com.android.systemui/u0a18} (pid=2005, uid=10018) that is not exported from uid 10257

传递参数FileProvider Uri,com.android.systemui无访问权限,导致设置的MP3无法播放

  1. adb shell dumpsys notification查看sound是否为设置的Urisound为设置的Uri,正常

解决办法

使用grantUriPermissions()

1
2
grantUriPermission("com.android.systemui", sound,
Intent.FLAG_GRANT_READ_URI_PERMISSION);

(这个具体情况可以根据上面分析中的Log确定包名)

使用android.resource

假设使用raw资源保存test.mp3文件,然后使用

1
Uri uri = Uri.parse("android.resource://“+ context.getPackageName() + R.id.test);
1
Uri uri = Uri.parse("android.resource://“+ context.getPackageName() + "/raw/test.mp3");

禁止严格模式&不使用FileProvider(不推荐)

1
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().build());

总结

  • Android7.0 注意Uri权限问题

  • Android8.0 注意setSound在NotificationChannel完成

参考

  1. Notifications, Sounds, Android 7.0, and Aggravation
  2. Google Issue Tracker
  3. Stackoverflow Issue
  4. Google Fixed
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×